<template>
  <div class="login">
    <canvas id="fullstarbg"></canvas>
    <div class="content">
      <img
        :src="rabit"
        class="rabitBg"
      />
      <!-- <img :src="text" class="rabittext" /> -->
    </div>
    <el-form
      :model="ruleForm2"
      status-icon
      :rules="rules2"
      ref="ruleForm2"
      label-width="0px"
      class="login-ruleForm log"
    >
      <el-row class="tips">
        <el-col :span="10">
          <div class="grid-content bg-purple">商家登录</div>
        </el-col>
        <el-col :span="14">
          <div class="grid-content bg-purple">没有账号？<span @click="back(0)">立即注册</span></div>
        </el-col>
      </el-row>
      <el-form-item prop="username">
        <el-input
          placeholder="请输入手机号码"
          v-model="ruleForm2.username"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请输入密码"
          type="password"
          @keyup.enter.native="submitForm('ruleForm2')"
          v-model="ruleForm2.password"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      </el-form-item>
      <el-row class="rember">
        <el-checkbox v-model="rember">记住我</el-checkbox>
        <router-link :to="{path:'/set'}"><span class="forget">忘记密码？</span></router-link>
      </el-row>
      <el-form-item class="submit">
        <el-button
          type="primary"
          @click="submitForm('ruleForm2')"
        >登录</el-button>
      </el-form-item>
    </el-form>

    <el-form
      :model="ruleForm1"
      status-icon
      :rules="rules1"
      ref="ruleForm1"
      label-width="0px"
      class="login-ruleForm rig-ruleForm rig"
    >
      <el-row class="tips">
        <el-col :span="10">
          <div class="grid-content bg-purple">商家注册</div>
        </el-col>
        <el-col :span="14">
          <div class="grid-content bg-purple">已有账号？<span @click="back(1)">立即登录</span></div>
        </el-col>
      </el-row>
      <el-form-item prop="username">
        <el-input
          placeholder="请输入用户名称"
          type="text"
          v-model="ruleForm1.username"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="phone">
        <el-input
          placeholder="请输入手机号码"
          type="tel"
          v-model="ruleForm1.phone"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="qq">
        <el-input
          placeholder="请输入QQ号"
          v-model="ruleForm1.qq"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      </el-form-item>
      <el-form-item
        prop="code"
        class="code"
      >
        <el-input
          placeholder="请输入短信验证码"
          v-model="ruleForm1.code"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
        <el-button
          type="warning"
          plain
          @click="getcode"
          :disabled="isget">{{button}}</el-button>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请设置密码"
          type="password"
          v-model="ruleForm1.password"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      </el-form-item>

      <el-form-item prop="inviter">
        <el-input
          placeholder="请输入邀请码 "
          v-model="ruleForm1.inviter"
          :disabled="dis"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      </el-form-item>
      <el-form-item class="submit">
        <el-button
          type="warning"
          plain
          @click="register('ruleForm1')"
        >注册</el-button>
        <el-button
          type="primary"
          @click="back(1)"
          plain
        >返回</el-button>

      </el-form-item>
    </el-form>

  </div>
</template>



<script>
import rabit from "@/assets/images/rabit.png";
import text from "@/assets/images/text.png";
import {login,registered,getcode} from '@/pages/api/index.js'
// import { userLogin, getcode, register } from "../../api/user";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };


    return {
      ruleForm2: {
        username: localStorage.getItem("USER_INFO_USERNAME") || "",
        password: localStorage.getItem("USER_INFO_PASSWORD") || ""
      },
      dis: true,
      ruleForm1: {
        phone: "",
        password: "",
        qq: null,
        code: null,
        inviter: "",
        username: ""
      },
      button: "获取验证码",
      rules2: {
        username: [{ validator: validatePass, trigger: "blur" }],
        password: [
          { validator: validatePass2, trigger: "blur" },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      },
      rules1: {
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        qq: [{ required: true, message: "请输入qq号码", trigger: "blur" }],

        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户昵称", trigger: "blur" }
        ]
      },
      islogin: true,
      rember: false,
      isget: false,
      rabit,
      text
    };
  },
  watch: {
    rember() {
      if (this.rember) {
      } else {
        localStorage.removeItem("USER_INFO_USERNAME");
        localStorage.removeItem("USER_INFO_PASSWORD");
      }
    },
    button() {
      if (this.button == "获取验证码") {
        this.isget = false;
      } else {
        this.isget = true;
      }
    }
  },
  methods: {
    //登录
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          login(this.ruleForm2)
            .then(res => {
              console.log(res,'res')
              if (res.code == 0) {
                this.$message.success("登陆成功 ");
                // this.$sore.commit('SET_TOKEN',res.token);
                this.$store.commit('setUsername',res.data.username)
                this.$store.commit('setUserkey',res.data.userKey)
                this.$store.commit('setMoney',res.data.store_money)
                if (this.rember) {
                  localStorage.setItem(
                    "USER_INFO_USERNAME",
                    this.ruleForm2.username
                  );
                  localStorage.setItem(
                    "USER_INFO_PASSWORD",
                    encodeURIComponent(this.ruleForm2.password)
                  );
                }
                console.log(23)
                setTimeout(() => {
                  this.$router.push({
                    path:'/',
                  });
                  console.log(12)
                }, 1000);
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(err => {});
        } else {
          return false;
        }
      });
    },
    //注册
    register(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
         /*  if(this.ruleForm1.password < 6 || this.ruleForm1.password > 18){
                   this.$message.warning('密码有效位为6-18位')
                   return
          } */
          registered(this.ruleForm1)
            .then(res => {
              if (res.code == 0) {
                this.$message.success("注册成功请登录 ");
                this.$refs.ruleForm1.$el.style.transform = "scale(0)";
                this.$refs.ruleForm2.$el.style.transform = "scale(1)";
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(err => {
            });
        } else {
          return false;
        }
      });
    },

    //获取邀请码
    getcode() {
      const that = this;
      if (!this.ruleForm1.phone) {
        // debugger
        this.$message.error("请输入手机号码 ");
        console.log(this.ruleForm1.username,1)
      } else {
        console.log(this.ruleForm1.username,2)
        getcode({phone:this.ruleForm1.phone})
          .then(res => {
            if (res.code == 0) {
              //  this.ruleForm1.code = res.data;
              this.$message.success("获取验证码成功");
              that.isget = true;
              var s = 60;
              var times = setInterval(() => {
                s--;
                that.button = `已发送(${s})秒`;
                if (s <= 0) {
                  clearInterval(times);
                  this.button = "获取验证码";
                }
              }, 1000);
            } else this.$message.error(res.msg);
          })
          .catch(err => {});
      }
    },

    //canvas初始化
    canvas() {
      /**
       * Created by Zcy on 2016/11/1 0001.
       */

      // window.addEventListener("load", windowload, false);
      // function windowload() {
      //   canvasApp();
      // }
      // function canvasSupport(){
      //     return Modernizr.canvas;
      // }

      //   if(!canvasSupport()){
      //       return;
      //   }
      var canvasElement = document.getElementById("fullstarbg");
      var cxt = canvasElement.getContext("2d");
      var windowW = window.innerWidth;
      var windowh = window.innerHeight;
      canvasElement.width = windowW;
      canvasElement.height = windowh;
      //画星星
      var nums = 200;
      var starArr = [];
      for (var i = 0; i < nums; i++) {
        var arrs = ["t", "f"];
        var r = Math.random() * 1; //生成星星的半径
        var ax = Math.random() * canvasElement.width;
        var ay = Math.random() * canvasElement.height;
        var opactityS = Math.random() * 1;
        opactityS = opactityS > 0.7 ? 0.7 : opactityS;
        var trues = arrs[Math.floor(Math.random() * 2)];

        starArr.push({
          x: ax,
          y: ay,
          R: r,
          initX: ax,
          initY: ay,
          moves: trues,
          initOpacity: opactityS,
          opacity: opactityS
        });
      }
      //流线

      var newLine = true;
      var linesArr = [];
      var conter = 0;
      function createLine() {
        if (newLine == true) {
          var lineNum = Math.ceil(Math.random() * 12);
          //#59576a;
          linesArr = [];
          for (var i = 0; i < lineNum; i++) {
            var lx = Math.random() * canvasElement.width;
            var ly =
              Math.random() * canvasElement.height - Math.random() * 10000;
            linesArr.push({
              initX: lx,
              initY: 0,
              length: Math.random() * 50 + 30,
              speed: Math.random() * 10
            });
          }
          newLine = false;
        }
      }
      //3秒之后让红色的圆形运动
      var redstart = false;
      // setTimeout(function(){
      //     redstart=true;
      // },3000);
      setInterval(function() {
        redstart = true;
      }, 3000);
      var yred = -0.25 * canvasElement.width * 0.22;
      var redYlimt = -0.35 * canvasElement.width * 0.22;
      function draw() {
        cxt.clearRect(0, 0, canvasElement.width, canvasElement.height);
        var colors = cxt.createLinearGradient(0, 0, 0, canvasElement.height);
        colors.addColorStop(0, "#090723");
        colors.addColorStop(0.75, "#090723");
        colors.addColorStop(1, "#08071e");
        cxt.fillStyle = colors; //08071e
        cxt.fillRect(0, 0, canvasElement.width, canvasElement.height);
        //画圆 color r x y
        drawCircle(
          "IndianRed",
          canvasElement.width * 0.12,
          0.44 * canvasElement.width,
          redYlimt,
          "#fcf6ac"
        ); //红
        drawCircle(
          "#201620",
          canvasElement.width * 0.025,
          0.95 * canvasElement.width,
          0.32 * canvasElement.height
        ); //灰
        drawCircle(
          "#140c2a",
          canvasElement.width * 0.01,
          0.75 * canvasElement.width,
          0.22 * canvasElement.height
        ); //紫
        drawCircle(
          "#090929",
          canvasElement.width * 0.018,
          0.82 * canvasElement.width,
          0.52 * canvasElement.height
        ); //蓝
        if (redstart == true) {
          redYlimt += 1;
        }
        if (redYlimt > yred) {
          redYlimt = yred;
        }
        //STAR
        for (var i = 0; i < starArr.length; i++) {
          var child = starArr[i];
          cxt.save();
          cxt.globalAlpha = child.opacity;
          cxt.beginPath();
          cxt.fillStyle = "#ffffff";
          cxt.arc(child.initX, child.initY, child.R, 0, Math.PI * 2, false);
          cxt.fill();
          cxt.closePath();
          //移动

          if (child.moves == "t") {
            child.initX -= Math.random() * 1 * 0.01; //星星移动的速度
            if (child.initX < 0) {
              child.initX = child.x;
            }
          }
          //透明度
          if (child.opacity < 0.8) {
            child.opacity += 0.005;
            if (child.opacity > 0.7) {
              child.opacity = child.initOpacity;
            }
          }
          cxt.restore();
        }
        //lines
        createLine();

        for (var i = 0; i < linesArr.length; i++) {
          var child = linesArr[i];
          cxt.save();
          cxt.rotate(0);
          cxt.beginPath();
          cxt.strokeStyle = "#59576a";
          cxt.moveTo(child.initX, child.initY);
          cxt.lineTo(
            child.initX - Math.cos((Math.PI / 180) * 45) * child.length,
            child.initY + Math.sin((Math.PI / 180) * 45) * child.length
          );
          cxt.stroke();
          cxt.restore();
          child.speed += 0.1;
          var preX = Math.cos((Math.PI / 180) * 45) * child.speed;
          var preY = Math.sin((Math.PI / 180) * 45) * child.speed;
          child.initX = child.initX - preX;
          child.initY = child.initY + preY;
          if (child.initX < 0 || child.initY > canvasElement.height) {
            conter = i + 1;
          }
          if (conter == linesArr.length) {
            conter = 0;
            newLine = true;
          }
        }
      }
      draw();
      setInterval(draw, 20);
      function drawCircle(color, R, x, y, color2) {
        cxt.beginPath();
        if (color2) {
          var gradient2 = cxt.createRadialGradient(x, y, R / 2, x, y, R);
          gradient2.addColorStop(0, color);
          gradient2.addColorStop(0.5, color);
          gradient2.addColorStop(1, color2);
          cxt.fillStyle = gradient2;
        } else {
          cxt.fillStyle = color;
        }

        var r = R;
        cxt.arc(x, y, R, 0, Math.PI * 2, false);
        cxt.fill();
        cxt.closePath();
      }
      //代码思路：
      //星星 随机产生一定数量的星星对象{初始位置:x,y;星星半径}
      //星星闪烁与运动的原理 每隔一定秒数重新绘制 并且移动位置 与 改变透明度  闪烁与移动可以随机或者一定的规律
      //
      //流线  同流星原理类似  斜线根据角度与第一点 求第二点
    },

    //返回登录
    back(index) {
      if (!index) {
        this.$refs.ruleForm2.$el.style.transform = "scale(0)";
        this.$refs.ruleForm1.$el.style.transform = "scale(1)";
      } else {
        this.$refs.ruleForm1.$el.style.transform = "scale(0)";
        this.$refs.ruleForm2.$el.style.transform = "scale(1)";
      }
    }
  },
  mounted() {
    if(this.$route.query.key) {
        this.$refs.ruleForm2.$el.style.transform = "scale(0)";
        this.$refs.ruleForm1.$el.style.transform = "scale(1)";
        this.ruleForm1.inviter = this.$route.query.key
        this.dis = true
    }else{
       this.dis = false
    }
    this.canvas();
  }
};
</script>

<style lang="scss">
.login {
  .log {
    transform: scale(1);
  }
  .rig {
    transform: scale(0);
  }
  @import url("../../assets/css/canvas.scss");
  width: 100%;
  height: 100%;
  // background-image: url("../../assets/images/login-bg.jpg");
  background-size: cover;
  background-position: center;
  position: relative;

  .login-ruleForm {
    box-shadow: 5px 5px 0px 0px rgba(0, 0, 0, 0.1);
    opacity: 0.9;
    display: block;
    z-index: 2;
    transition: 1s all;
    width: 300px;
    position: absolute;
    right: 280px;
    top: 250px;
    background-color: #fff;
    border-radius: 6px;
    padding: 20px;
    .el-form-item {
      width: 90%;
      margin: 20px auto;
    }
    input {
      height: 45px;
      font-size: 18px;
      // letter-spacing: 2px;
    }
    input::-webkit-input-placeholder {
      // color: #add8e6;
      font-size: 14px;
    }
    .submit {
      display: flex;
      justify-content: space-around;
      margin-bottom: 0;
      text-align: center;
      width: 85%;
      > div {
        width: 100%;
        button {
          width: 100%;
          height: 45px;
          margin-left: 0;
          margin-bottom: 10px;
        }
      }
    }
    .tips {
      padding-bottom: 20px;
      .el-col-10 {
        font-family: "微软雅黑";
        font-size: 26px;
        vertical-align: middle;
      }
      .el-col-14 {
        vertical-align: middle;
        line-height: 35px;
        span {
          color: #ff6600;
        }
      }
      span {
        cursor: pointer;
      }
    }
    .rember {
      display: flex;
      justify-content: space-between;
      padding: 0 20px 15px 20px;
      font-family: "宋体";
      .forget {
        font-size: 14px;
        color: #ff6600;
      }
    }
  }
  .rig-ruleForm {
    z-index: 1;
    top: 120px;
    .code {
      position: relative;
      left: 0;
      top: 0;
      button {
        position: absolute;
        right: 10px;
        top: 10%;
        height: 80%;
        padding:0 5px !important;
        text-align: center;
        padding: 0;
      }
    }
  }
}
</style>

